import requests
import os
import time
import datetime
import argparse

def get_commit_list(base_url: str, access_token: str, owner_name: str, repo_name: str, page: int, per_page: int, since: str, until: str):
    url = f"{base_url}/repos/{owner_name}/{repo_name}/commits"
    params = {
        "access_token": access_token,
        "page": page,
        "per_page": per_page,
        "since": since,
        "until": until,
    }
    response = requests.get(url, params=params)
    return response.json()

def get_org_repos(base_url: str, access_token: str, org_name: str, page: int, per_page: int) -> list:
    url = f"{base_url}/orgs/{org_name}/repos"
    params = {
        "access_token": access_token,
        "page": page,
        "per_page": per_page
    }
    response = requests.get(url, params=params)
    return response.json()

def get_monday_sunday_of_week():
    monday = (time.time() - time.localtime().tm_wday * 86400)
    monday = monday - (monday % 86400) + time.timezone
    sunday = time.time() + (6 - time.localtime().tm_wday) * 86400
    sunday = sunday - (sunday % 86400) + 86399 + time.timezone
    monday -= 86400 * 7
    sunday -= 86400 * 7
    monday_iso = datetime.datetime.fromtimestamp(monday).isoformat()
    sunday_iso = datetime.datetime.fromtimestamp(sunday).isoformat()
    monday_ymd = monday_iso.split("T")[0]
    sunday_ymd = sunday_iso.split("T")[0]
    return monday_iso, sunday_iso, monday_ymd, sunday_ymd

def get_ymd_from_iso(iso: str):
    return iso.split("T")[0]

def gen_changelog_weekly_task(base_url: str, access_token: str, output_dir: str, since: str, until: str):
    monday_ymd, sunday_ymd, monday_iso, sunday_iso = '', '', '', ''
    if since and until:
        monday_ymd = get_ymd_from_iso(since)
        sunday_ymd = get_ymd_from_iso(until)
        monday_iso = since
        sunday_iso = until
    else:
        # get last week monday and sunday
        monday_iso, sunday_iso, monday_ymd, sunday_ymd = get_monday_sunday_of_week()


    print("start request repos...")
    # get all repos of oh-sdu
    page = 1
    per_page = 100
    repos = []
    while True:
        org_repos = get_org_repos(base_url, access_token, oh_sdu_org, page, per_page)
        if len(org_repos) == 0:
            break
        repos.extend(org_repos)
        page += 1

    print("repos count:", len(repos))

    print("start generate changelog...")
    os.makedirs(output_dir, exist_ok=True)
    os.chdir(output_dir)
    filename = f"{monday_ymd} {sunday_ymd}.md"
    with open(filename, "w", encoding="utf-8") as f:
        # get commit list of each repo
        for repo in repos:
            time.sleep(5)
            print(f"start generate changelog of {repo['full_name']}...")
            parent = repo["parent"]
            if not parent:
                continue
            full_name = repo["parent"]["full_name"]
            owner_name, repo_name = full_name.split("/")
            if owner_name != openharmony_org:
                continue

            page = 1
            per_page = 100
            commits = []
            while True:
                commit_list = get_commit_list(base_url, access_token, openharmony_org, repo_name, page, per_page, monday_iso, sunday_iso)
                if len(commit_list) == 0:
                    break
                commits.extend(commit_list)
                page += 1
            
            if len(commits) == 0:
                continue

            # write changelog as markdown
            f.write(f"# {repo_name}\n")
            for commit in commits:
                message = commit["commit"]["message"]
                html_url = commit["html_url"]
                first_line = message.split("\n")[0]
                f.write(f"- [{first_line}]({html_url})\n")
    
    print(f"changelog generated: {filename}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.description = "Generate weekly changelog for OpenHarmony"
    parser.add_argument("--token", type=str, help="gitee access token", required=True)
    parser.add_argument("--base-url", type=str, default="https://gitee.com/api/v5", help="base URL for the Gitee API")
    parser.add_argument("--output-dir", type=str, default="changelog", help="output directory for the changelog")
    parser.add_argument("--since", type=str, help="start date in ISO format (e.g., 2025-03-01T00:00:00Z)")
    parser.add_argument("--until", type=str, help="end date in ISO format (e.g., 2025-03-07T23:59:59Z)")
    args = parser.parse_args()
    # TODO: if we want to change the org name or the upstream org name, modify the following two variables to command line arguments
    oh_sdu_org = "oh-sdu"
    openharmony_org = "openharmony"
    gen_changelog_weekly_task(args.base_url, args.token, args.output_dir, args.since, args.until)